package com.tanhua.manage.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserFreeze;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.pojo.UserLoginLogs;
import com.tanhua.common.service.UserFreezeService;
import com.tanhua.common.service.UserLoginLogsService;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.manage.pojo.Distribution;
import com.tanhua.manage.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Ling
 * @Title: null.java
 * @Package com.tanhua.manage.service
 * @Description:
 * @date 2021/9/11 16:29
 */
@Service
@Slf4j
public class ManageService {
    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private UserInfoService userInfoService;

//    @Autowired
//    private UserFreezeMapper userFreezeMapper;

    //    @Autowired
//    private UserLoginLogsMapper loginLogsMapper;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private UserLoginLogsService userLoginLogsService;

    @Autowired
    private UserService userService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 获取用户上传的视频列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    public PageResult getVideosListByUserId(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //此处为依据传递过来的字段与排序方法进行排序 因字段名与数据库不符 废弃
//        PageRequest pageRequest = null;
//        if (ObjectUtil.isAllNotEmpty(sortOrder, sortProp)) {
//            Sort sort = Sort.by(Sort.Order.desc(sortProp));
//            if (sortOrder.startsWith("asc")) {
//                sort = Sort.by(Sort.Order.asc(sortProp));
//            }
//            pageRequest = PageRequest.of(page - 1, pageSize, sort);
//        }
//        PageInfo<Video> videoListByUserId = videoApi.getVideoListByUserId(userId, page, pageSize, pageRequest);
        PageInfo<Video> videoListByUserId = videoApi.getVideoListByUserId(userId, page, pageSize);

        List<Video> records = videoListByUserId.getRecords();

        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);

        List<VideosVo> videosVoList = new ArrayList<>();
        Integer IdCount = 0;
        for (Video record : records) {
            VideosVo videosVo = new VideosVo();

            videosVo.setId(++IdCount);
            videosVo.setUserId(userId);
            videosVo.setPicUrl(record.getPicUrl());
            videosVo.setVideoUrl(record.getVideoUrl());
            videosVo.setCreateDate(record.getCreated());

            videosVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(record.getId().toHexString())));
            videosVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(record.getId().toHexString())));
            videosVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(record.getId().toHexString())));
            videosVo.setReportCount(0);

            //todo 循环嵌套可能导致性能问题
            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(videosVo.getUserId(), userInfo.getUserId())) {
                    videosVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            videosVoList.add(videosVo);
        }
        pageResult.setItems(videosVoList);
        return pageResult;
    }

    /**
     * 置顶用户消息
     *
     * @param id
     * @return
     */
    public Map<String, String> topMessages(String id) {
        Publish publish = quanZiApi.queryPublishById(id);
        Map<String, String> map = new HashMap<>();
        if (quanZiApi.topMessages(publish.getUserId(), id)) {
            map.put("message", "操作成功");
        } else {
            map.put("message", "操作失败");
        }
        return map;
    }

    /**
     * 取消置顶
     *
     * @param id
     * @return
     */
    public Map<String, String> untopMessages(String id) {
        Publish publish = quanZiApi.queryPublishById(id);
        Map<String, String> map = new HashMap<>();
        if (quanZiApi.untopMessages(publish.getUserId(), id)) {
            map.put("message", "操作成功");
        } else {
            map.put("message", "操作失败");
        }
        return map;
    }

    /**
     * 获取用户动态的评论列表
     *
     * @param messageID
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    //todo 未测试
    public PageResult getComments(String messageID, Integer page, Integer pageSize, String sortProp, String sortOrder) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
//        PageRequest pageRequest = null;
//        if (ObjectUtil.isAllNotEmpty(sortOrder, sortProp)) {
//            Sort sort = Sort.by(Sort.Order.desc(sortProp));
//            if (sortOrder.startsWith("asc")) {
//                sort = Sort.by(Sort.Order.asc(sortProp));
//            }
//            pageRequest = PageRequest.of(page - 1, pageSize, sort);
//        }
//
//        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(messageID, page, pageSize, pageRequest);
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(messageID, page, pageSize);

        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<CommentsVo> result = new ArrayList<>();
        List<Object> userId = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userId);
        Map<Long, String> map = new HashMap<>();
        for (UserInfo userInfo : userInfoList) {
            map.put(userInfo.getUserId(), userInfo.getNickName());
        }
        int IdCount = 0;
        for (Comment record : records) {

            CommentsVo commentsVo = new CommentsVo();
            commentsVo.setId(++IdCount + "");
            commentsVo.setContent(record.getContent());
            commentsVo.setCreateDate(record.getCreated());
            if (map.containsKey(record.getUserId())) {
                commentsVo.setUserId(record.getUserId());
                commentsVo.setNickname(map.get(record.getUserId()));
                result.add(commentsVo);
            }
        }
        pageResult.setItems(result);
        return pageResult;
    }

    /**
     * 获取单条动态详情
     *
     * @param id
     * @return
     */
    public MessagesVo getMessage(String id) {
        MessagesVo messagesVo = new MessagesVo();
        try {
            Publish publish = quanZiApi.queryPublishById(id);
            UserInfo userInfo = userInfoService.queryUserInfoByUserId(publish.getUserId());

            messagesVo.setId(publish.getId().toHexString());
            messagesVo.setUserId(userInfo.getUserId());
            messagesVo.setNickname(userInfo.getNickName());
            messagesVo.setUserLogo(userInfo.getLogo());
            messagesVo.setCreateDate(publish.getCreated());
            messagesVo.setText(publish.getText());
            messagesVo.setMedias(publish.getMedias());
            messagesVo.setState(2);//todo 审核状态
            messagesVo.setTopState(quanZiApi.queryMessageIsTop(userInfo.getUserId(), publish.getId().toHexString()) ? 2 : 1);
            messagesVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(publish.getId().toHexString())));
            messagesVo.setReportCount(0);
            messagesVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(publish.getId().toHexString())));
            messagesVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(publish.getId().toHexString())));
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        return messagesVo;
    }

    /**
     * 获取用户登录日志
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    public PageResult getLoginLogs(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
//        QueryWrapper<UserLoginLogs> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_id", userId);
//        wrapper.orderByDesc("login_time");
////        wrapper.orderByDesc(sortProp);
////        if (sortOrder.startsWith("asc")){
////            wrapper.orderByAsc(sortProp);
////        }
////        List<UserLoginLogs> userLoginLogs = loginLogsMapper.selectList(wrapper);
//        Page<UserLoginLogs> iPage = new Page<>(page, pageSize);
//        IPage<UserLoginLogs> userLoginLogs = loginLogsMapper.selectPage(iPage, wrapper);
//        List<UserLoginLogs> records = userLoginLogs.getRecords();

        IPage<UserLoginLogs> loginLogs = userLoginLogsService.getLoginLogs(userId, page, pageSize, sortProp, sortOrder);
        List<UserLoginLogs> records = loginLogs.getRecords();
        List<UserLoginLogsVo> result = new ArrayList<>();
        for (UserLoginLogs record : records) {
            UserLoginLogsVo userLoginLogsVo = new UserLoginLogsVo();
            userLoginLogsVo.setLoginTime(DateUtil.format(record.getLoginTime(), "yyyy-MM-dd hh:mm:ss"));
            userLoginLogsVo.setId(record.getId());
            userLoginLogsVo.setLocation(record.getLocation());
            userLoginLogsVo.setEquipment(record.getEquipment());
            userLoginLogsVo.setUserId(record.getUserId());
            result.add(userLoginLogsVo);
        }
        pageResult.setCounts(records.size());
        pageResult.setPages(Convert.toInt(loginLogs.getPages()));
        pageResult.setItems(result);
        return pageResult;
    }

    /**
     * 冻结用户
     *
     * @return
     */
//    public Map<String, String> freezeUser(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
    public Map<String, String> freezeUser(UserFreeze freeze) {
        Map<String, String> map = new HashMap<>();
        if (userFreezeService.freezeUser(freeze)) {
            map.put("message", "操作成功");
            return map;
        }
        map.put("message", "操作失败");
        return map;
    }


    /**
     * 解冻用户
     *
     * @param userId            用户id
     * @param reasonsForThawing 解冻原因
     * @return
     */
    public Map<String, String> unfreezeUser(Long userId, String reasonsForThawing) {
        Map<String, String> map = new HashMap<>();
        if (userFreezeService.unfreezeUser(userId, reasonsForThawing)) {
            map.put("message", "操作成功");
            return map;
        }
        map.put("message", "操作失败");
        return map;
    }


    public PageResult getUsersList(Integer page, Integer pageSize, Integer id, String nickname, String city) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        IPage<UserInfo> usersList = userInfoService.getUsersList(page, pageSize, id, nickname, city);
        List<UserInfo> records = usersList.getRecords();
        pageResult.setCounts(Convert.toInt(usersList.getTotal()));
        pageResult.setPages(Convert.toInt(usersList.getPages()));
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<User> users = userService.queryUsersByUserIdList(userIds);
        if (CollUtil.isEmpty(userIds)) {
            return pageResult;
        }
        Map<Long, String> userPhoneMap = new HashMap<>();
        for (User user : users) {
            userPhoneMap.put(user.getId(), user.getMobile());
        }
        List<UserFreeze> userFreezes = userFreezeService.getUserFreezeByUserIdList(userIds);
        Map<Long, String> userFreezesMap = new HashMap<>();
        for (UserFreeze freeze : userFreezes) {
            userFreezesMap.put(freeze.getUserId(), freeze.getReasonsForFreezing());
        }
        List<UsersListVo> list = new ArrayList<>();
        for (UserInfo record : records) {
            UsersListVo usersListVo = new UsersListVo();
            usersListVo.setId(record.getUserId());
            usersListVo.setLogo(record.getLogo());
            usersListVo.setLogoStatus("1");
            usersListVo.setNickname(record.getNickName());
            usersListVo.setSex(record.getSex().getValue() == 1 ? "男" : "女");
            usersListVo.setAge(record.getAge());
            usersListVo.setOccupation(record.getIndustry());
            usersListVo.setCity(record.getCity());
            usersListVo.setLastActiveTime(0L);//todo 最近活跃时间

            if (userPhoneMap.containsKey(usersListVo.getId())) {
                usersListVo.setMobile(userPhoneMap.get(usersListVo.getId()));
            }
            usersListVo.setUserStatus("1");
            if (userFreezesMap.containsKey(usersListVo.getId())) {
                usersListVo.setUserStatus("2");
            }

            list.add(usersListVo);


        }
        pageResult.setItems(list);
        return pageResult;
    }

    public UsersInfoVo getUsersInfo(Long id) {

        User user = null;
        UserInfo userInfo = null;
        UserLoginLogs latestLoginLog = null;
        try {
            user = userService.queryUserByUserId(id);
            userInfo = userInfoService.queryUserInfoByUserId(id);
            latestLoginLog = userLoginLogsService.getLatestLoginLog(id);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

        return fillUsersInfoVo(id, user, userInfo, latestLoginLog);
    }

    private UsersInfoVo fillUsersInfoVo(Long id, User user, UserInfo userInfo, UserLoginLogs latestLoginLog) {
        UsersInfoVo usersInfoVo = new UsersInfoVo();
        if (ObjectUtil.isAllNotEmpty(id, user, userInfo, latestLoginLog)) {
            usersInfoVo.setId(user.getId());
            usersInfoVo.setNickname(userInfo.getNickName());
            usersInfoVo.setMobile(user.getMobile());
            usersInfoVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
            usersInfoVo.setPersonalSignature("个性签名");//todo 个性签名
            usersInfoVo.setAge(userInfo.getAge());
            usersInfoVo.setCountBeLiked(Convert.toInt(userLikeApi.queryFanCount(id)));
            usersInfoVo.setCountLiked(Convert.toInt(userLikeApi.queryLikeCount(id)));
            usersInfoVo.setCountMatching(Convert.toInt(userLikeApi.queryMutualLikeCount(id)));
            usersInfoVo.setIncome(Convert.toInt(userInfo.getIncome()));
            usersInfoVo.setOccupation(userInfo.getIndustry());
            usersInfoVo.setUserStatus(userFreezeService.isFrozen(id) ? "2" : "1");
            usersInfoVo.setCreated(user.getCreated().getTime());
            usersInfoVo.setCity(userInfo.getCity());
            usersInfoVo.setLastActiveTime(latestLoginLog.getLoginTime().getTime());
            usersInfoVo.setLastLoginLocation(latestLoginLog.getLocation());
            usersInfoVo.setLogo(userInfo.getLogo());
            usersInfoVo.setTags(userInfo.getTags());
            return usersInfoVo;
        }
        return null;
    }

    public PageResult getMessages(Long uid, Integer page, Integer pageSize, String sortProp, String sortOrder) {
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(uid, page, pageSize);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<Publish> records = pageInfo.getRecords();
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(uid);
        List<MessagesVo> result = new ArrayList<>();

        for (Publish record : records) {
            MessagesVo messagesVo = new MessagesVo();
            messagesVo.setId(record.getId().toHexString());
            messagesVo.setNickname(userInfo.getNickName());
            messagesVo.setUserId(userInfo.getUserId());
            messagesVo.setUserLogo(userInfo.getLogo());
            messagesVo.setCreateDate(record.getCreated());
            messagesVo.setText(record.getText());
            messagesVo.setMedias(record.getMedias());
            messagesVo.setState(2);
            messagesVo.setTopState(quanZiApi.queryMessageIsTop(uid, record.getId().toHexString()) ? 1 : 2);
            messagesVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(record.getId().toHexString())));
            messagesVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(record.getId().toHexString())));
            messagesVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(record.getId().toHexString())));
            messagesVo.setReportCount(0);
            result.add(messagesVo);
        }
        pageResult.setPages(pageInfo.getPageNum());
        pageResult.setCounts(pageInfo.getTotal());
        pageResult.setItems(result);

        return pageResult;
    }
}
